package edu.cs.usask.ca.silver.businesslogic.util;

import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.commons.pool.impl.SoftReferenceObjectPool;
import org.apache.log4j.Logger;

/**
 * Implementation of SilverPoolableObjectFactory using Apache Commons
 * SoftReferenceObjectPool.
 * 
 * The pool is self-grow and do not need extra effort in object management.
 * Unused objects will be automatically invalidated and then collected by
 * garbage collector
 * 
 * @author Yudi Xue
 * 
 */
public class SilverAutoManagedObjectFactory {

	private SoftReferenceObjectPool sPool;
	private static Logger logger = Logger.getLogger(SilverAutoManagedObjectFactory.class);

	public SilverAutoManagedObjectFactory(final String className) {
		sPool = new SoftReferenceObjectPool(new BasePoolableObjectFactory() {
			@Override
			public Object makeObject() throws Exception {
				if (className == null) {
					throw new ClassNotFoundException("no classname defined");
				}
				return Class.forName(className).newInstance();

			}
		});

	}

	public Object borrowObject() {
		try {
			return sPool.borrowObject();
		} catch (Exception e) {
			logger.warn("failed to borrow object");
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * edu.cs.usask.ca.silver.api.businesslogic.factory.SilverPoolableObjectFactory
	 * #returnObject(java.lang.Object)
	 */
	public void returnObject(Object returnItem) {
		try {
			sPool.returnObject(returnItem);
		} catch (Exception e) {
			logger.warn("failed to return object");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * edu.cs.usask.ca.silver.api.businesslogic.factory.SilverPoolableObjectFactory
	 * #printOutPoolInfo()
	 */
	public void printOutPoolInfo() {
		System.out.println("actual active: " + sPool.getNumActive());
		System.out.println("actual idle: " + sPool.getNumIdle());
	}
	
	public String getOutPoolInfo() {
		return "\r\n Object pool status: \r\n actual active: " + sPool.getNumActive() + "\r\n actual idle: " + sPool.getNumIdle();
	}
	
	public void logPoolInfo() {
		logger.info("actual active: " + sPool.getNumActive());
		logger.info("actual idle: " + sPool.getNumIdle());
	}

}
